//
//  ZQOAuthViewController.swift
//  Timor微博
//
//  Created by 周周旗 on 2019/4/8.
//  Copyright © 2019 ZQ. All rights reserved.
//

import UIKit
import WebKit
import SVProgressHUD
class ZQOAuthViewController: UIViewController {
    
    private lazy var webView = WKWebView()
    
    override func loadView() {
        view = webView
        webView .navigationDelegate = self
        view.backgroundColor = UIColor.white
        webView.scrollView.isScrollEnabled = false
        self.title = "登录新浪微博"
        //导航栏按钮
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", target: self, action: #selector(close), isBackItem: true)
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动授权", target: self, action: #selector(autoFill), isBackItem: false)

    }
    override func viewDidLoad() {
        super.viewDidLoad()
        
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(WBAPPKey)&redirect_uri=\(WBRedirectURI)"
        //1> url 访问资源
        
        guard let url = URL(string: urlString) else {
            return
        }
        //2> 建立请求
        let request = URLRequest(url: url)
        //3> 加载请求
        webView.load(request)
    }

    
    @objc private func close() {
        SVProgressHUD.dismiss()
        dismiss(animated: true, completion: nil)
    }
    
    /// webView的注入，直接通过js修改`本地浏览器中缓存的页面内容`
    @objc private func autoFill(){
        let js = "document.getElementById('userId').value = '18202806601';" + "document.getElementById('passwd').value = 'zhouqi19920524.';"
        webView.evaluateJavaScript(js) { (json, error) in
            print(error as Any)
        }
    }
}

// MARK: - 执行代理
extension ZQOAuthViewController:WKNavigationDelegate{
    
    func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
        print("请求数据---\(String(describing: navigationAction.request.url?.absoluteString))")
        //1.如果请求地址包含 https://baid.com 不加载页面/否则加载页面
        if navigationAction.request.url?.absoluteString.hasPrefix("https://www.baidu.com") == false{
            decisionHandler(.allow)
            return
        }
        //2.从http://baidu.com回调地址的`查找字符串`中查找`code=`
        //如果有授权成功，否则授权失败
        if navigationAction.request.url?.query?.hasPrefix("code=") == false{
            close()
            decisionHandler(.cancel)
            return
        }
        //3. 从quary字符串中取出 授权码
        let query = navigationAction.request.url?.query
        guard let code = query?["code=".endIndex...] else {
            print("获取授权码失败")
            return
        }
        print("获取授权码...\(code )")
        //4. 使用授权码获取 AccessToken
        ZQNetWorkManager.shared.loadAccessToken(code: String(code))
        decisionHandler(.allow)
        
    }
    func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
        SVProgressHUD.show()
    }
    
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        SVProgressHUD.dismiss()
    }
    
}

